Default Jupyter Notebook

This notebook will present a basic setup of makesense.

First, we will import some settings from the JSON settings file. It contains all the relevant files location.


In [ ]:
import json
import os
from os.path import join as pj

from jinja2 import Environment, FileSystemLoader

# The root of the contiki project used
CONTIKI_FOLDER = None

# Location where the fabfile is
ROOT_DIR = None

# Where all the experiment and results are stored
EXPERIMENT_FOLDER = None

# Location of all the templates
TEMPLATE_FOLDER = None

# Location of the COOJA simulator used
COOJA_DIR = None

# Where the notebook is
path = os.path.dirname(__file__)

with open(pj(path, "settings.json")) as f:
    settings = json.loads(f.read())
    CONTIKI_FOLDER = settings["CONTIKI_FOLDER"]
    ROOT_DIR = settings["ROOT_DIR"]
    EXPERIMENT_FOLDER = settings["EXPERIMENT_FOLDER"]
    TEMPLATE_FOLDER = settings["TEMPLATE_FOLDER"]
    COOJA_DIR = settings["COOJA_DIR"]
    TUNSLIP6 = settings["TUNSLIP6"]
    TEMPLATE_ENV = Environment(loader=FileSystemLoader(TEMPLATE_FOLDER))

In [ ]:
import subprocess

def _make_nodes(target="wismote"):
    client_template = TEMPLATE_ENV.get_template("dummy_client.c")
    with open(pj(path, "dummy-client.c"), "w") as f:
        f.write(client_template.render())

    server_template = TEMPLATE_ENV.get_template("dummy_server.c")
    with open(pj(path, "dummy-server.c"), "w") as f:
        f.write(server_template.render())

    makefile_template = TEMPLATE_ENV.get_template("dummy_makefile")
    with open(pj(path, "Makefile"), "w") as f:
        f.write(makefile_template.render(contiki=CONTIKI_FOLDER,
                                         target=target))

def _make_sim_file(title="Dummy Simulation",
                   random_seed=12345,
                   transmitting_range=42,
                   interference_range=42,
                   timeout=10000000, 
                   success_ratio_tx=1.0,
                   success_ratio_rx=1.0,
                   powertracker_frequency=10000):
    main_csc_template = TEMPLATE_ENV.get_template("dummy_main.csc")
    script_template = TEMPLATE_ENV.get_template("dummy_script.js")
    script = script_template.render(
        timeout=timeout,
        powertracker_frequency=powertracker_frequency,
    )
    with open(pj(path, "main.csc"), "w") as f:
        f.write(main_csc_template.render(
            title=title,
            random_seed=random_seed,
            transmitting_range=transmitting_range,
            interference_range=interference_range,
            success_ratio_tx=success_ratio_tx,
            success_ratio_rx=success_ratio_rx,
            mote_types=[
                {"name": "server", 
                 "description": "server",
                 "commands": "make er-example-server.wismote TARGET=wismote",
                 "source": "[CONTIKI_DIR]/examples/er-rest-example/er-example-server.c",
                 "firmware": "[CONTIKI_DIR]/examples/er-rest-example/er-example-server.wismote"},
                {"name": "br", 
                 "description": "Border router",
                 "commands": "make border-router.wismote TARGET=wismote",
                 "source": "[CONTIKI_DIR]/examples/ipv6/rpl-border-router/border-router.c",
                 "firmware": "[CONTIKI_DIR]/examples/ipv6/rpl-border-router/border-router.wismote"}
            ],
            motes=[
                {"mote_id": 1, "x": 0, "y": 0, "z": 0, "mote_type": "br"},
                {"mote_id": 2, "x": 1, "y": 1, "z": 0, "mote_type": "server"},
            ],
            script=script))

def _compile_cooja():
    subprocess.call(["ant", "jar"], cwd=COOJA_DIR)

def _compile_nodes(target="wismote"):
    subprocess.call(["make", "TARGET=%s" % target], cwd=path)
    
def make():
    _make_nodes()
    _make_sim_file()
    _compile_cooja()
    _compile_nodes()

# This line will be launched when running the cell and when the CI script is generated
# When we only want to import functions, the function won't be runned.
if __name__ == "__main__":
    make()

In [ ]:
from multiprocessing import Process, Manager
import requests
from time import sleep

def _coap_process(dest, sleep_time=2):
    while True:
        subprocess.call(["coap", "get", dest])
        sleep(sleep_time)

def _tunslip():
    subprocess.call(["make", "connect-router-cooja"], cwd=path)

def _run_cooja():
    subprocess.call(["make", "run"], cwd=path)

def _cache_setup(c):
    req = requests.put('http://localhost:5000/cache', data={"cache": c})
    print("cache time set to %d" % c)
    print(req.status_code)

def _proxy_cache():
    """
    Code for our reverse proxy cache.
    A redis database is requiered.
    """
    subprocess.call(["python", "cache.py"], cwd=path)

def _ping_process(dest, c):
    """
    Create ping traffic:
    
    :dest destination
    :c count of packets sent
    """
    subprocess.call(["ping6", "-I", "tun0", dest, "-c", str(c)])
    
def launch_cooja(c=3, timeout=100):
    manager = Manager()
    hit, miss, sleep_time = manager.dict(), manager.dict(), manager.dict()
    # Il faut gérer le tunslip, l'injection de traffic, la collecte des résultats
    # et le simulateur
    processes = {
        "cooja": Process(target=_run_cooja),
        "tunslip": Process(target=_tunslip),
        #"traffic": Process(target=_gen_traffic),
        "ping1": Process(target=_ping_process,
                        args=("fd00::200:0:0:1", 30)),
        "ping2": Process(target=_ping_process,
                args=("fd00::200:0:0:2", 30)),
        "coap": Process(target=_coap_process,
                       args=("coap://[fd00::200:0:0:2]/test/hello",))
        #"cache_setup": Process(target=_cache_setup,
        #                       args=(c,)),
        #"reverse_proxy": Process(target=_proxy_cache)
    }
    processes["cooja"].start()
    sleep(15)
    processes["tunslip"].start()
    sleep(10)
    processes["ping1"].start()
    processes["ping2"].start()
    processes["coap"].start()
    #processes["reverse_proxy"].start()
    
    #processes["cache_setup"].start()
    
    processes["cooja"].join(timeout)
    for name, p in processes.items():
        if p.is_alive():
            print("Terminating %s" % name)
            p.terminate()

# This line will be launched when running the cell and when the CI script is generated
# When we only want to import functions, the function won't be runned.
if __name__ == "__main__":
    launch_cooja()

In [23]:
import iotlabcli
from iotlabcli import experiment
import json
from multiprocessing import Process

def upload_iotlab(testbed_name="grenoble", testbed_duration=10):
    user, passwd = iotlabcli.get_user_credentials()
    api = iotlabcli.Api(user, passwd)
    
    resources_config = [
      {
        "nodes": [
          "m3-53.grenoble.iot-lab.info",
          "m3-54.grenoble.iot-lab.info"
        ],
        "firmware_path": "er-coap-server.iotlab-m3",
        "profile_name": "m3_energy_monitoring"
      },
      {
        "nodes": [
          "m3-55.grenoble.iot-lab.info"
        ],
        "firmware_path": "er-coap-server.iotlab-m3",
        "profile_name": "m3_packet_energy_monitoring"
      },
      # We need a PCAP sniffer
      {
        "nodes": [
            "m3-56.grenoble.iot-lab.info"
        ],
        "firmware_path": "border-router.iotlab-m3",
        "profile_name": "m3_energy_monitoring"
      }
    ]
    resources = [experiment.exp_resources(**c) for c in resources_config]
    exp_res = experiment.submit_experiment(
            api, 
            testbed_name, testbed_duration, 
            resources)
    testbed_experiment_id = exp_res["id"]
    with open("experiment.json", "w") as f:
        f.write(json.dumps({"id": testbed_experiment_id}))

    # get the content
    print("Exp submited with id: %u" % testbed_experiment_id)

def launch_ssh_tunnel(target, testbed_name="grenoble",
                      home_port=2000, iotlab_port=20000):
    """
    Will launch a SSH tunnel. We need it to perform a tunslip on our host.
    """
    subprocess.call(["ssh", "-vNT", 
                     testbed_name, 
                     "-L", "%d:%s:%d" % (home_port, target, iotlab_port)])

def launch_tunslip_iotlab(prefix="aaaa::1/64", target="localhost", home_port=2000):
    """
    Will start a tunslip
    """
    subprocess.call(["sudo", TUNSLIP6, prefix, "-L", "-a", target, "-p", home_port])

def launch_serial_aggregator():
    """
    Collect the text with serial aggregator
    """
    print("Lancement de l'aggregator")

def launch_iotlab():
    processes = {
        "upload_iotlab": Process(target=upload_iotlab),
        "ssh_tunnel": Process(target=launch_ssh_tunnel),
        #"tunslip": Process(target=launch_tunslip_iotlab),
        #"traffic": Process(target=_gen_traffic),
        #"cache_setup": Process(target=_cache_setup,
        #                       args=(c,)),
        #"reverse_proxy": Process(target=_proxy_cache)
    }
    processes["upload_iotlab"].start()
    processes["upload_iotlab"].join()
    processes["ssh_tunnel"].start()

if __name__ == "__main__":
    launch_iotlab()


Exp submited with id: 37107

In [ ]:
def analyze():
    print("I am the analyze step")

# This line will be launched when running the cell and when the CI script is generated
# When we only want to import functions, the function won't be runned.
if __name__ == "__main__":
    analyze()

In [ ]:
def plot():
    print("I am the plot step")

# This line will be launched when running the cell and when the CI script is generated
# When we only want to import functions, the function won't be runned.
if __name__ == "__main__":
    plot()